package com.maxverse.boot.web2image.service.impl;

import com.maxverse.boot.web2image.common.model.TaskMessage;
import com.maxverse.boot.web2image.common.service.TaskProcessService;
import com.maxverse.boot.web2image.core.constant.TaskStatus;
import com.maxverse.boot.web2image.screenshot.service.ScreenshotExecutor;
import com.maxverse.boot.web2image.storage.entity.Task;
import com.maxverse.boot.web2image.storage.file.FileStorage;
import com.maxverse.boot.web2image.storage.repository.TaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.time.LocalDateTime;

@Slf4j
@Service
public class TaskProcessServiceImpl implements TaskProcessService {

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private FileStorage fileStorage;

    @Autowired
    private ScreenshotExecutor screenshotExecutor;

    @Override
    @Transactional
    public void processTask(TaskMessage message) {
        String taskId = message.getTaskId();
        log.info("Processing task: {}", taskId);

        Task task = taskRepository.findByTaskId(taskId)
                .orElseThrow(() -> new RuntimeException("Task not found: " + taskId));

        int maxRetries = 3;
        int retryCount = 0;
        Exception lastException = null;

        while (retryCount < maxRetries) {
            try {
                // 更新任务状态为处理中
                task.setStatus(TaskStatus.PROCESSING);
                task.setUpdateTime(LocalDateTime.now());
                taskRepository.save(task);

                // 准备输出路径
                String fileName = taskId + "." + message.getFormat().toLowerCase();
                Path outputPath = fileStorage.getOutputPath(fileName);

                // 执行截图
                Path resultPath = screenshotExecutor.takeScreenshot(message, outputPath);

                // 更新任务状态为成功
                task.setStatus(TaskStatus.SUCCESS);
                task.setResultPath(resultPath.toString());
                task.setUpdateTime(LocalDateTime.now());
                taskRepository.save(task);

                log.info("Task completed successfully: {}", taskId);
                return;
            } catch (Exception e) {
                lastException = e;
                retryCount++;
                log.warn("Failed to process task: {} (attempt {}/{})", taskId, retryCount, maxRetries, e);
                
                // 短暂等待后重试
                try {
                    Thread.sleep(2000 * retryCount);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }

        // 所有重试都失败了
        log.error("All retry attempts failed for task: {}", taskId, lastException);
        task.setStatus(TaskStatus.FAILED);
        task.setErrorMsg(lastException.getMessage());
        task.setRetryCount(task.getRetryCount() + retryCount);
        task.setUpdateTime(LocalDateTime.now());
        taskRepository.save(task);
    }
} 